<template>
  <!-- v-pagePermissions="pagePermissions"  -->
  <div class="white-bg commonBoxmp">
    <div class="aic HeightAuto">
      <deptTree @updateDept="handleNodeClick"></deptTree>
      <TableV2
        class="flex1"
        @getHeight="getHeight"
        :pageInfo="pageInfo"
        :searchBool="true"
        :column="state.columnData"
        @getCurrentColumns="getCurrentColumns"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      >
        <template #tableHeader>
          <div class="jcb aic w100">
            <h3 class="mx15">用户管理</h3>
            <el-button type="primary" @click="handleAddUser"
              >添加用户</el-button
            >
          </div>
        </template>

        <template #tableContent>
        <el-skeleton
              class="p20"
              :loading="state.height == 0"
              animated
              :rows="19"
            >
              <template #default>
                <el-table
                  :height="state.height"
                  :data="state.tableData"
                  @current-change="handleCurrentChangeRow"
                >
                  <el-table-column type="index"></el-table-column>
                  <el-table-column
                    v-for="(item, index) in state.columnData"
                    :key="index"
                    :label="item.label"
                    :prop="item.prop"
                  >
                    <template
                      v-if="item.render && item.prop == 'status'"
                      #default="scope"
                    >
                      <el-switch
                        active-value="0"
                        inactive-value="1"
                        @change="handleStatusChange(scope.row)"
                        v-model="scope.row.status"
                      >
                      </el-switch>
                    </template>
                    <template
                      v-if="item.render && item.prop == 'createTime'"
                      #default="scope"
                    >
                      {{ parseTime(scope.row.createTime) }}
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" fixed="right" width="150px" align="left">
                    <template #default="scope">
                        <el-button
                        type="text"
                        @click="handleUpdate( scope.row)"
                        >修改</el-button
                      >
                      <el-button
                          type="text"
                        @click="handleDelete( scope.row)"
                        >删除</el-button
                      >
                    </template>
                  </el-table-column>
                </el-table>
              </template>
            </el-skeleton>
        </template>
      </TableV2>

    </div>
      <el-dialog
    v-model="state.userVisible"
    :title="state.title"
    width="50%"
    destroy-on-close
    center
  >
    <el-form
    ref="ruleFormRef"
    :model="state.form"
    :rules="state.rules"
    label-width="120px"
    class="demo-ruleForm"
    status-icon
  >
  <el-row :gutter="20">
<el-col :span="12">
    <el-form-item label="用户昵称" prop="nickName">
      <el-input v-model="state.form.nickName" />
    </el-form-item>
</el-col>
<el-col :span="12">
  <el-form-item label="归属部门" prop="deptId">
       <el-cascader :options="state.deptOptions" v-model="state.form.deptId"  :props=" {
  checkStrictly: true,
}" clearable />
    </el-form-item>
</el-col>
  </el-row>
    <el-row :gutter="20">
<el-col :span="12">
    <el-form-item label="手机号码" prop="phonenumber">
      <el-input v-model="state.form.phonenumber" />
    </el-form-item>
</el-col>
<el-col :span="12">
  <el-form-item label="邮箱" prop="email">
        <el-input v-model="state.form.email" />
    </el-form-item>
</el-col>
  </el-row>
    

  </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, getCurrentInstance, onMounted,toRaw } from "vue";
import { useRouter, useRoute } from "vue-router";
import Card from "/@/views/dashboard/analysis/card.vue";
import * as echarts from "echarts";
import deptTree from "/@/views/system/user/components/deptTree.vue";
import Column from "/@ts/components/table/Column";
import formatTool from "/@ts/hooks/format";
import {
  listUser,
  getUser,
  delUser,
  addUser,
  updateUser,
  resetUserPwd,
  changeUserStatus,
  deptTreeSelect,
} from "/@ts/axios/urlApi/system/user";
import { ElMessage, ElMessageBox, FormInstance } from "element-plus";
const router = useRouter();
const route = useRoute();
const { parseTime,addDateRange } = formatTool();
// const ruleFormRef = ref<FormInstance>()
const ruleFormRef = ref<FormInstance>()
const dialogVisible = ref(true);
const state: any = reactive({
  height: 0,
  deptOptions:[],
  form:{},
      // 表单校验
      rules: {
        userName: [
          { required: true, message: "用户名称不能为空", trigger: "blur" },
          { min: 2, max: 20, message: '用户名称长度必须介于 2 和 20 之间', trigger: 'blur' }
        ],
        nickName: [
          { required: true, message: "用户昵称不能为空", trigger: "blur" }
        ],
        password: [
          { required: true, message: "用户密码不能为空", trigger: "blur" },
          { min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur' }
        ],
        email: [
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ],
        phonenumber: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ]
      },
  dateRange:[],
  postOptions:[],
  roleOptions:[],
  tableData: [],
  columnData: [
    {
      label: "用户名称",
      prop: "userName",
    },
    {
      label: "用户昵称",
      prop: "nickName",
    },
    {
      label: "部门",
      prop: "dept.deptName",
    },

    {
      label: "手机号",
      prop: "phonenumber",
    },
    {
      label: "状态",
      prop: "status",
      render: true,
    },
    {
      label: "创建时间",
      prop: "createTime",
      render: true,
    },
  ],
  loading:false,
});
const pageInfo = reactive({
  currentPage: 1,
  total: 10,
  pageSize: 10,
  pageSizes: [10, 20, 30, 40],
  layout: "total, prev, pager, next,sizes",
});
const queryParams = reactive({
        pageNum: 1,
        pageSize: 10,
        deptId:undefined
})
const getCurrentColumns = (data: Column[]) => {
  state.columnData = data;
};
const getHeight = (height: number) => {
  state.height = height;
};
const handleSizeChange = (size: number) => {
  pageInfo.pageSize = size;
};
const handleCurrentChange = (page: number) => {
  pageInfo.currentPage = page;
};
   /** 搜索按钮操作 */
   const handleQuery =()=> {
     queryParams.pageNum = 1;
      getList();
    }
//切换部门数据
 const handleNodeClick =(data:any)=> {
  
      queryParams.deptId = data.id;
      handleQuery();
    }
// 用户状态修改
const handleStatusChange = (row: any) => {
  let text = row.status === "0" ? "启用" : "停用";

  ElMessageBox.confirm('确认要"' + text + '""' + row.userName + '"用户吗？')
    .then(function() {
      const data = {
        userId: row.userId,
        status: row.status,
      };
      return changeUserStatus(data);
    })
    .then(() => {
      ElMessage.success(text + "成功");
    })
    .catch(function() {
      row.status = row.status === "0" ? "1" : "0";
    });
};
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
    await formEl.validate()
}
const handleDelete= (row: any) => {
 const userIds = row.userId ;
  ElMessageBox.confirm('是否确认删除用户编号为"' + userIds + '"的数据项？')
    .then(function() {
      return delUser(userIds);
    })
    .then(() => {
      ElMessage.success("删除成功");
    })
    .catch(function() {
    });
};
 /** 修改按钮操作 */
const handleUpdate = (row:any) =>{
     const userId = row.userId;
      getUser(userId).then((response:any) => {
        console.log('response :>> ', response);
       state.title = "修改用户";
        state.form = response.data;
                state.postOptions = response.posts;
        state.roleOptions = response.roles;
        state.form.password = "";
        state.userVisible = true;
        }
      );
}
//查询用户列表
const getList = () =>{
     state.loading = true;
      listUser(addDateRange(queryParams, state.dateRange)).then((response:any) => {
          state.tableData = response.rows;
          pageInfo.total = response.total;
          state.loading = false;
        }
      );
}
   /** 查询部门下拉树结构 */
 const  getDeptTree=()=> {
      deptTreeSelect().then((response:any) => {
        state.deptOptions = response.data;
      });
    }
onMounted(() => {
  getList()
  getDeptTree()
});
</script>

<style scoped lang="scss"></style>
